package com.ztgf.shopping.service.shop;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.qiyuesuo.sdk.v2.SdkClient;
import com.qiyuesuo.sdk.v2.bean.*;
import com.qiyuesuo.sdk.v2.json.JSONUtils;
import com.qiyuesuo.sdk.v2.param.SignParam;
import com.qiyuesuo.sdk.v2.request.ContractDraftRequest;
import com.qiyuesuo.sdk.v2.request.ContractPageRequest;
import com.qiyuesuo.sdk.v2.request.ContractSignCompanyRequest;
import com.qiyuesuo.sdk.v2.response.ContractPageResult;
import com.qiyuesuo.sdk.v2.response.SdkResponse;
import com.qiyuesuo.sdk.v2.utils.CryptUtils;
import com.qiyuesuo.sdk.v2.utils.MD5;
import com.ztgf.common.utils.DateUtils;
import com.ztgf.common.utils.StrUtils;
import com.ztgf.logistics.models.dto.deppon.LogisticsUserContractDTO;
import com.ztgf.logistics.models.dto.deppon.LogisticsUserDTO;
import com.ztgf.logistics.models.service.deppon.ILogisticsUserContractService;
import com.ztgf.logistics.models.service.deppon.ILogisticsUserService;
import com.ztgf.pay.models.dto.PayUserDTO;
import com.ztgf.pay.models.service.IPayUserService;
import com.ztgf.shopping.common.config.YmlConfig;
import com.ztgf.shopping.mapper.shop.ShopContractSettleInMapper;
import com.ztgf.shopping.models.bo.shop.ShopContractSettleInBO;
import com.ztgf.shopping.models.bo.shop.ShopContractSettleInSaveBO;
import com.ztgf.shopping.models.bo.shop.ShopQiyuesuoInfoLogSaveBO;
import com.ztgf.shopping.models.bo.template.ContractStatusCallBackBO;
import com.ztgf.shopping.models.dto.audit.AuditDeBangDTO;
import com.ztgf.shopping.models.dto.shop.ShopContractSettleInDTO;
import com.ztgf.shopping.models.dto.shop.ShopInfoDTO;
import com.ztgf.shopping.models.dto.shop.ShopQiyuesuoInfoDTO;
import com.ztgf.shopping.models.service.audit.IAuditDebangService;
import com.ztgf.shopping.models.service.shop.IShopContractSettleInService;
import com.ztgf.shopping.models.vo.shop.ShopContractSettleInVO;
import com.ztgf.shopping.models.vo.shop.ShopInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * author: chenyu.wang
 * date: 2020-07-10 14:27
 * Description: 商家入驻合同表控制器
 */
@Slf4j
@DubboService
public class ShopContractSettleInServiceImpl extends ServiceImpl<ShopContractSettleInMapper, ShopContractSettleInDTO> implements IShopContractSettleInService {
    @Value("${shop.qiyuesuo.service.sdkUrl}")
    private String serverUrl;

    @Value("${shop.qiyuesuo.service.appToken}")
    private String accessKey;

    @Value("${shop.qiyuesuo.service.appSecret}")
    private String accessSecret;

    @Value("${shop.qiyuesuo.service.companyName}")
    private String companyName;

    @Value("${shop.qiyuesuo.service.signNumber}")
    private String signNumber;

    @Value("${shop.qiyuesuo.settle.secretKey}")
    private String secretKey;

    @Value("${shop.qiyuesuo.settle.businessId}")
    private String settleBusinessId;

    @Value("${shop.qiyuesuo.debang.secretKey}")
    private String deBangsecretKey;

    @Value("${shop.qiyuesuo.debang.businessId}")
    private String deBangBusinessId;

    @Value("${page.show.url}")
    private String pageShowUrl;

    @Resource
    private YmlConfig ymlConfig;
    @Autowired
    private ShopQiyuesuoInfoServiceImpl shopQiyuesuoInfoService;
    @Autowired
    @Lazy
    private ShopInfoServiceImpl shopInfoService;
    @Autowired
    private ShopReceiveCardServiceImpl shopReceiveCardService;
    @Autowired
    private ShopQiyuesuoInfoLogServiceImpl shopQiyuesuoInfoLogService;
    @DubboReference
    private IPayUserService iPayUserService;
    @DubboReference
    private ILogisticsUserContractService iLogisticsUserContractService;

    @DubboReference
    private ILogisticsUserService iLogisticsUserService;
    @DubboReference
    private IAuditDebangService auditDebangService;

    /**
     * 获取所有未签署入驻合同的合同信息
     * @param LastNo
     * @return
     */
    @Override
    public List<ShopContractSettleInDTO> getNotSignContact(Long LastNo){
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("status", 0);
        wrapper.gt("shop_id", LastNo);
        wrapper.orderBy("shop_id", true);
        return baseMapper.selectPage(new Page<>(0, 50), wrapper);
    }


    @Override
    public Page<ShopContractSettleInVO> queryAdminPageList(ShopContractSettleInBO bo) {
        Page<ShopContractSettleInVO> pages = new Page<>(bo.getPageNo(), bo.getPageSize());
        List<ShopContractSettleInVO> list = baseMapper.queryAdminPageList(pages, bo);
        pages.setRecords(list);
        return pages;
    }

    @Override
    public ShopContractSettleInVO getById(Long id) {
        return baseMapper.getById(id);
    }

    @Override
    public boolean add(ShopContractSettleInSaveBO saveBO) {
        ShopContractSettleInDTO dto = new ShopContractSettleInDTO();
        dto.setShopId(saveBO.getShopId());
        dto.setContractUrl(saveBO.getContractUrl());
        dto.setContractLockId(saveBO.getContractLockId());
        dto.setId(ymlConfig.getPkId());
        return this.insert(dto);
    }

    @Override
    public ShopContractSettleInDTO getByShopId(Long shopId){
        Wrapper<ShopContractSettleInDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("shop_id", shopId);
        return this.selectOne(wrapper);
    }

    @Override
    public ShopContractSettleInDTO getByName(String name){
        Wrapper<ShopContractSettleInDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("name", name);
        return this.selectOne(wrapper);
    }


    public String createContract(Long shopId) throws Exception {
        SdkClient client = new SdkClient(serverUrl, accessKey, accessSecret);

        /**
         * 根据业务分类配置进行合同发起，文件、签署流程、签署公章、签署位置均在业务分类中维护
         * 该场景模拟一个人事合同的场景，即平台方公司与员工签署合同，平台方公司先签署，员工后签
         */

        SdkResponse<Contract> draft = draft(client, shopId);

        log.info("创建合同草稿成功，并发起，合同ID：{}", draft.getResult().getId());
        //companySealSignByCategoryConfig(client, draft.getResult().getId());
        log.info("公章签署成功");
        /**
         * 平台方签署完成，签署方签署可采用
         * （1）接收短信的方式登录契约锁云平台进行签署
         * （2）生成内嵌页面签署链接进行签署（下方生成的链接）
         * （3）JS-SDK签署（仅支持个人）
         */
        return draft.getResult().getId() + "";
    }

    /**
     * 根据业务分类配置创建合同草稿并发起合同
     *
     * @param client
     * @return
     * @throws Exception
     */
    private SdkResponse<Contract> draft(SdkClient client, Long shopId) throws Exception {
        ShopQiyuesuoInfoLogSaveBO shopQiyuesuoInfoLogSaveBO = new ShopQiyuesuoInfoLogSaveBO();//契约锁日志
        ShopQiyuesuoInfoDTO shopQiyuesuoInfoDTO = shopQiyuesuoInfoService.getByShopId(shopId);
        ShopInfoVO shopInfoVO =  shopInfoService.selectVoById(shopId);
        PayUserDTO payUserDTO = iPayUserService.getPayUserDTO(shopId,1);
        Contract draftContract = new Contract();
        draftContract.setExpireTime(DateUtils.dateToStr(DateUtils.addYear( DateUtils.getCurrentDate(),1)));//设置过期时间
        draftContract.setSubject("合同主题");
        draftContract.setCategory(new Category(Long.parseLong(settleBusinessId))); // 设置业务分类ID,套用该业务分类的配置
        draftContract.addTemplateParam(new TemplateParam("name", shopInfoVO.getName()));//公司名称
        draftContract.addTemplateParam(new TemplateParam("legalPerson", shopInfoVO.getLegalPerson()));//法人
        draftContract.addTemplateParam(new TemplateParam("address", shopInfoVO.getAddress()));//地址
        draftContract.addTemplateParam(new TemplateParam("creditCode", shopInfoVO.getCreditCode()));//信用代码，税号
        draftContract.addTemplateParam(new TemplateParam("mobile", shopInfoVO.getContactName() + shopInfoVO.getMobile()));//手机号
        draftContract.addTemplateParam(new TemplateParam("email", shopInfoVO.getEmail()));//邮箱
        if (payUserDTO != null){
            draftContract.addTemplateParam(new TemplateParam("bankCardNo", payUserDTO.getZjBankElectronicNo()));//账号
            draftContract.addTemplateParam(new TemplateParam("bankName", payUserDTO.getZjBankName()));//银行
        }

        // 设置接收方详情，接收方需要与业务分类中设置的签署方流程匹配
        // 公司签署方
        Signatory companySignatory = new Signatory();
        companySignatory.setTenantName(companyName);
        companySignatory.setTenantType("COMPANY");
        companySignatory.setReceiver(new User(signNumber, "MOBILE"));
        companySignatory.setSerialNo(1);
        draftContract.addSignatory(companySignatory);
        // 公司签署方
        Signatory personalSignatory = new Signatory();
        personalSignatory.setTenantType("COMPANY");
        personalSignatory.setReceiver(new User(shopQiyuesuoInfoDTO.getContact(), shopQiyuesuoInfoDTO.getContactType()));
        personalSignatory.setTenantName(shopQiyuesuoInfoDTO.getCompanyName());
        draftContract.addSignatory(personalSignatory);
        draftContract.setSend(true); // 创建合同草稿并发起合同

        ContractDraftRequest contractDraftRequest = new ContractDraftRequest(draftContract);
        shopQiyuesuoInfoLogSaveBO.setRequetsParam(JSON.toJSONString(contractDraftRequest));
        shopQiyuesuoInfoLogSaveBO.setType(0);
        shopQiyuesuoInfoLogSaveBO.setInfoType(0);

        String response = null;
        try {
            response = client.service(contractDraftRequest);
        } catch (Exception e) {
            shopQiyuesuoInfoLogSaveBO.setStatus(1);
            shopQiyuesuoInfoLogSaveBO.setResponseParam(e.getMessage());
            shopQiyuesuoInfoLogService.add(shopQiyuesuoInfoLogSaveBO);
            throw new Exception("创建合同草稿请求服务器失败，失败原因：" + e.getMessage());
        }
        SdkResponse<Contract> sdkResponse = JSONUtils.toQysResponse(response, Contract.class);
        if (!sdkResponse.getCode().equals(0)) {
            shopQiyuesuoInfoLogSaveBO.setStatus(1);
            shopQiyuesuoInfoLogSaveBO.setResponseParam(sdkResponse.getMessage());
            shopQiyuesuoInfoLogService.add(shopQiyuesuoInfoLogSaveBO);
            throw new Exception("创建合同草稿失败，失败原因：" + sdkResponse.getMessage());
        }
        shopQiyuesuoInfoLogSaveBO.setStatus(0);
        shopQiyuesuoInfoLogSaveBO.setResponseParam(JSON.toJSONString(sdkResponse));
        shopQiyuesuoInfoLogService.add(shopQiyuesuoInfoLogSaveBO);
        return sdkResponse;
    }

    /**
     * 根据业务分类配置的签署位置与印章签署公章
     * 若未配置签署位置需要设置签署位置与印章
     *
     * @param client
     * @param contractId
     * @return
     * @throws Exception
     */
    private SdkResponse companySealSignByCategoryConfig(SdkClient client, Long contractId) throws Exception {
        SignParam param = new SignParam();
        param.setContractId(contractId);

        String response = null;
        try {
            response = client.service(new ContractSignCompanyRequest(param));
        } catch (Exception e) {
            throw new Exception("公章签署请求服务器失败，失败原因：" + e.getMessage());
        }
        SdkResponse sdkResponse = JSONUtils.toQysResponse(response, Object.class);
        if (!sdkResponse.getCode().equals(0)) {
            throw new Exception("公章签署失败，失败原因：" + sdkResponse.getMessage());
        }
        return sdkResponse;
    }


    /**
     * 生成用户的签署链接
     *
     * @return
     * @throws Exception
     */
    public String gerenateSignUrl(Long shopId) throws Exception {
        ShopContractSettleInDTO shopContractSettleInDTO = getByShopId(shopId);
        if(null == shopContractSettleInDTO){
            return "";
        }
        ShopQiyuesuoInfoDTO shopQiyuesuoInfoDTO = shopQiyuesuoInfoService.getByShopId(shopId);

        SdkClient client = new SdkClient(serverUrl, accessKey, accessSecret);
        User signUser = new User(shopQiyuesuoInfoDTO.getContact(), shopQiyuesuoInfoDTO.getContactType());
        String callbackPage = pageShowUrl + "/sleStore/sleStoreMessage";
        ContractPageRequest request = new ContractPageRequest(Long.parseLong(shopContractSettleInDTO.getContractLockId()), signUser, callbackPage);

        String response;
        try {
            response = client.service(request);
        } catch (Exception e) {
            throw new Exception("生成签署链接请求服务器失败，失败原因：" + e.getMessage());
        }
        SdkResponse<ContractPageResult> sdkResponse = JSONUtils.toQysResponse(response, ContractPageResult.class);
        if (!sdkResponse.getCode().equals(0)) {
            throw new Exception("法人章签署失败，失败原因：" + sdkResponse.getMessage());
        }
        log.info("生成签署链接成功，签署地址：{}", sdkResponse.getResult().getPageUrl());
        return sdkResponse.getResult().getPageUrl();
    }


    /**
     * 生成德邦的签署链接
     *
     * @return
     * @throws Exception
     */
    public String gerenateDBSignUrl(Long shopId,Long id) throws Exception {
        //ShopContractSettleInDTO shopContractSettleInDTO = getByShopId(shopId);
        LogisticsUserContractDTO logisticsUserContractDTO = iLogisticsUserContractService.selectById(id);
        if(null == logisticsUserContractDTO){
            return "";
        }
        ShopQiyuesuoInfoDTO shopQiyuesuoInfoDTO = shopQiyuesuoInfoService.getByShopId(shopId);

        SdkClient client = new SdkClient(serverUrl, accessKey, accessSecret);
        User signUser = new User(shopQiyuesuoInfoDTO.getContact(), shopQiyuesuoInfoDTO.getContactType());
        String callbackPage = pageShowUrl + "/home/personCenter/logistics";
        ContractPageRequest request = new ContractPageRequest(Long.parseLong(logisticsUserContractDTO.getContractId()), signUser, callbackPage);

        String response;
        try {
            response = client.service(request);
        } catch (Exception e) {
            throw new Exception("生成签署链接请求服务器失败，失败原因：" + e.getMessage());
        }
        SdkResponse<ContractPageResult> sdkResponse = JSONUtils.toQysResponse(response, ContractPageResult.class);
        if (!sdkResponse.getCode().equals(0)) {
            throw new Exception("法人章签署失败，失败原因：" + sdkResponse.getMessage());
        }
        log.info("生成签署链接成功，签署地址：{}", sdkResponse.getResult().getPageUrl());
        return sdkResponse.getResult().getPageUrl();
    }

    @Override
    public String updateContactByCallBackInfo(String signature,String timestamp,String content) throws Exception {
        ShopQiyuesuoInfoLogSaveBO shopQiyuesuoInfoLogSaveBO = new ShopQiyuesuoInfoLogSaveBO();
        shopQiyuesuoInfoLogSaveBO.setStatus(0);
        shopQiyuesuoInfoLogSaveBO.setInfoType(1);
        shopQiyuesuoInfoLogSaveBO.setType(0);
        shopQiyuesuoInfoLogSaveBO.setResponseParam("加密内容：" + content + "--时间搓：" + content + "--signature" + signature);
        shopQiyuesuoInfoLogService.add(shopQiyuesuoInfoLogSaveBO);

        MD5 md5 = new MD5(timestamp + secretKey);
        String encryptMessage = md5.compute();
        String decrypt = null;
        if(encryptMessage.equals(signature)){//解密相同
            decrypt = CryptUtils.aesDerypt(content, secretKey);
        }
        ContractStatusCallBackBO contractStatusCallBackBO = JSON.parseObject(decrypt, ContractStatusCallBackBO.class);
        if(null == contractStatusCallBackBO){
            return "success";
        }
        if(StrUtils.isNotEmpty(contractStatusCallBackBO.getTenantName())){
            ShopContractSettleInDTO shopContractSettleInDTO = getByName(contractStatusCallBackBO.getTenantName());

            ShopContractSettleInDTO dto = new ShopContractSettleInDTO();
            dto.setStartDate(new Date());
            dto.setEndDate(DateUtils.addYear(new Date(), 1));
            dto.setId(shopContractSettleInDTO.getId());
            dto.setStatus(1);//0未签订，1已签订
            dto.setSignTime(DateUtils.getCurrentDateTime());
            this.updateById(dto);

            //修改店铺信息表
            ShopInfoDTO shopInfoDTO = new ShopInfoDTO();
            shopInfoDTO.setId(shopContractSettleInDTO.getShopId());
            shopInfoDTO.setCheckAgreementStatus(1);//入住协议签订状态 0未签订，1已签订
            shopInfoService.updateById(shopInfoDTO);
        }
        log.info(decrypt);
        return "success";
    }

    @Override
    public String getContractString(Long contractId) {
        return shopQiyuesuoInfoService.getContractString(contractId);
    }

    @Override
    public boolean createShopContract(Long id) {
        ShopInfoDTO shopInfoDTO = shopInfoService.selectById(id);

        ShopContractSettleInDTO shopContractSettleInDTO = getByShopId(id);
        if (shopContractSettleInDTO != null){
            return false;
        }

        String contractLockId = "";
        try {
            contractLockId = this.createContract(id);
        } catch (Exception e) {
            log.info("入驻协议，报错信息：" + e.getMessage());
            return false;
        }
        ShopContractSettleInDTO dto = new ShopContractSettleInDTO();
        dto.setShopId(id);
        dto.setName(shopInfoDTO.getName());
        dto.setContractLockId(contractLockId);
        dto.setContractName(shopInfoDTO.getName() + "入驻协议");
        dto.setStatus(0);//0未签订，1已签订
        return this.insert(dto);

    }

    @Override
    public boolean createDeBangContract(Long id,Long id1) {
        ShopInfoDTO shopInfoDTO = shopInfoService.selectById(id);
        //LogisticsUserContractDTO logisticsUserContractDTO=iLogisticsUserContractService.selectById(id1);
        String contractLockId = "";
        try {
            log.info("--------------------------------1");
            contractLockId = this.createDBontract(id);
            log.info("--------------------------------2");
            log.info("--------------------------------"+contractLockId);
        } catch (Exception e) {
            log.info("合同协议，报错信息：" + e.getMessage());
            return false;
        }
        LogisticsUserContractDTO logisticsUserContractDTO1 = new LogisticsUserContractDTO();
        logisticsUserContractDTO1.setShopId(id);
       // logisticsUserContractDTO1.setName();
        logisticsUserContractDTO1.setContractId(contractLockId);
        logisticsUserContractDTO1.setTempletName(shopInfoDTO.getName() + "物流月结协议");
        logisticsUserContractDTO1.setStatus(0);
        logisticsUserContractDTO1.setId(id1);
        return iLogisticsUserContractService.updateById(logisticsUserContractDTO1);
    }

    @Override
    public String getCallBackDeBangContactInfo(String signature, String timestamp, String content) {
        ShopQiyuesuoInfoLogSaveBO shopQiyuesuoInfoLogSaveBO = new ShopQiyuesuoInfoLogSaveBO();
        shopQiyuesuoInfoLogSaveBO.setStatus(0);
        shopQiyuesuoInfoLogSaveBO.setInfoType(1);
        shopQiyuesuoInfoLogSaveBO.setType(0);
        shopQiyuesuoInfoLogSaveBO.setResponseParam("加密内容：" + content + "--时间搓：" + content + "--signature" + signature);
        shopQiyuesuoInfoLogService.add(shopQiyuesuoInfoLogSaveBO);

        MD5 md5 = new MD5(timestamp + deBangsecretKey);
        String encryptMessage = md5.compute();
        log.info("===============encryptMessage"+encryptMessage);
        log.info("===============signature"+signature);
        String decrypt = null;
        if(encryptMessage.equals(signature)){//解密相同
            try {
                decrypt = CryptUtils.aesDerypt(content, deBangsecretKey);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        ContractStatusCallBackBO contractStatusCallBackBO = JSON.parseObject(decrypt, ContractStatusCallBackBO.class);
        if(null == contractStatusCallBackBO){
            return "success";
        }
        log.info("======================contractStatusCallBackBO"+contractStatusCallBackBO);
        if(StrUtils.isNotEmpty(contractStatusCallBackBO.getContractId())){
            LogisticsUserContractDTO logisticsUserContractDTO = iLogisticsUserContractService.getByName(contractStatusCallBackBO.getContractId());
            if (contractStatusCallBackBO.getContractStatus().equals("COMPLETE")){
                LogisticsUserContractDTO dto = new LogisticsUserContractDTO();
                //dto.setStartDate(new Date());
                // dto.setEndDate(DateUtils.addYear(new Date(), 1));
                dto.setId(logisticsUserContractDTO.getId());
                dto.setStatus(1);//0未签订，1已签订
                dto.setSignTime(DateUtils.getCurrentDateTime());
                dto.setEndDate(DateUtils.addYear(DateUtils.getCurrentDateTime(),1));
                log.info("==============dto"+dto);
                iLogisticsUserContractService.updateById(dto);

                LogisticsUserDTO logisticsUserDTO = iLogisticsUserService.selectById(logisticsUserContractDTO.getShopId());
                log.info("==============logisticsUserDTO"+logisticsUserDTO);
                if (logisticsUserDTO!=null){
                    logisticsUserDTO.setContractStatus(1);
                    iLogisticsUserService.updateById(logisticsUserDTO);
                }
                if((logisticsUserDTO.getMguaranteeMoney().compareTo(logisticsUserDTO.getMguaranteeMoneyQuota())) >-1){
                    logisticsUserDTO.setType(1);
                    iLogisticsUserService.updateById(logisticsUserDTO);
                }
            }else {
                LogisticsUserContractDTO dto = new LogisticsUserContractDTO();
                //dto.setStartDate(new Date());
                // dto.setEndDate(DateUtils.addYear(new Date(), 1));
                dto.setId(logisticsUserContractDTO.getId());
                dto.setStatus(2);//0未签订，1已签订
                dto.setSignTime(DateUtils.getCurrentDateTime());
                dto.setEndDate(DateUtils.addYear(DateUtils.getCurrentDateTime(),1));
                iLogisticsUserContractService.updateById(dto);
                LogisticsUserDTO logisticsUserDTO = iLogisticsUserService.selectById(logisticsUserContractDTO.getShopId());
                log.info("==============logisticsUserDTO"+logisticsUserDTO);
                if (logisticsUserDTO!=null){
                    logisticsUserDTO.setContractStatus(2);
                    iLogisticsUserService.updateById(logisticsUserDTO);
                }
            }



//            //修改店铺信息表
//            ShopInfoDTO shopInfoDTO = new ShopInfoDTO();
//            shopInfoDTO.setId(shopContractSettleInDTO.getShopId());
//            shopInfoDTO.setCheckAgreementStatus(1);//入住协议签订状态 0未签订，1已签订
//            shopInfoService.updateById(shopInfoDTO);
        }
        log.info(decrypt);
        return "success";
    }


    public String createDBontract(Long shopId) throws Exception {
        SdkClient client = new SdkClient(serverUrl, accessKey, accessSecret);

        SdkResponse<Contract> draft = draftByDebang(client, shopId);

        log.info("创建合同草稿成功，并发起，合同ID：{}", draft.getResult().getId());
        //companySealSignByCategoryConfig(client, draft.getResult().getId());
        log.info("公章签署成功");

        return draft.getResult().getId() + "";
    }

    private SdkResponse<Contract> draftByDebang(SdkClient client, Long shopId) throws Exception {
        LogisticsUserDTO logisticsUserDTO = iLogisticsUserService.selectById(shopId);
        ShopQiyuesuoInfoLogSaveBO shopQiyuesuoInfoLogSaveBO = new ShopQiyuesuoInfoLogSaveBO();//契约锁日志

        ShopQiyuesuoInfoDTO shopQiyuesuoInfoDTO = shopQiyuesuoInfoService.getByShopId(shopId);
       // log.info("shopQiyuesuoInfoDTO==========="+shopQiyuesuoInfoDTO.getId());
        ShopInfoVO shopInfoVO =  shopInfoService.selectVoById(shopId);
        //log.info("shopInfoVO==========="+shopInfoVO.getId());
        PayUserDTO payUserDTO = iPayUserService.getPayUserDTO(shopId,1);
        Contract draftContract = new Contract();
        draftContract.setExpireTime(DateUtils.dateToStr(DateUtils.addYear( DateUtils.getCurrentDate(),1)));//设置过期时间
        draftContract.setSubject("合同主题");
        draftContract.setCategory(new Category(Long.parseLong(deBangBusinessId))); // 设置业务分类ID,套用该业务分类的配置
        draftContract.addTemplateParam(new TemplateParam("name", shopInfoVO.getName()));//公司名称
        draftContract.addTemplateParam(new TemplateParam("legalPerson", shopInfoVO.getLegalPerson()));//法人
        draftContract.addTemplateParam(new TemplateParam("address", shopInfoVO.getAddress()));//地址
        draftContract.addTemplateParam(new TemplateParam("creditCode", shopInfoVO.getCreditCode()));//信用代码，税号
        draftContract.addTemplateParam(new TemplateParam("mobile", shopInfoVO.getContactName() + shopInfoVO.getMobile()));//手机号
        draftContract.addTemplateParam(new TemplateParam("email", shopInfoVO.getEmail()));//邮箱
        draftContract.addTemplateParam(new TemplateParam("userName", shopInfoVO.getContactName()));//
        draftContract.addTemplateParam(new TemplateParam("userPhone", shopInfoVO.getMobile()));//
        draftContract.addTemplateParam(new TemplateParam("userAddress", shopInfoVO.getAddress()));//

        if (payUserDTO != null){
            draftContract.addTemplateParam(new TemplateParam("bankCardNo", payUserDTO.getZjBankElectronicNo()));//账号
            draftContract.addTemplateParam(new TemplateParam("bankName", payUserDTO.getZjBankName()));//银行
        }
        if (logisticsUserDTO!=null){
            AuditDeBangDTO auditDeBangDTO = auditDebangService.selectById(logisticsUserDTO.getAuditId());
            if (auditDeBangDTO!=null){
                draftContract.addTemplateParam(new TemplateParam("sendName", auditDeBangDTO.getSendName()));//法人
                draftContract.addTemplateParam(new TemplateParam("sendPhone", auditDeBangDTO.getSendPhone()));//地址
                draftContract.addTemplateParam(new TemplateParam("sendWx", auditDeBangDTO.getSendWx()));//信用代码，税号
                draftContract.addTemplateParam(new TemplateParam("sendQq", auditDeBangDTO.getSendQq()));//手机号
                draftContract.addTemplateParam(new TemplateParam("financeName", auditDeBangDTO.getFinanceName()));//邮箱
                draftContract.addTemplateParam(new TemplateParam("financePhone", auditDeBangDTO.getFinancePhone()));//
                draftContract.addTemplateParam(new TemplateParam("financeWx", auditDeBangDTO.getFinanceWx()));//
                draftContract.addTemplateParam(new TemplateParam("financeQq", auditDeBangDTO.getFinanceQq()));//
            }

        }

        // 设置接收方详情，接收方需要与业务分类中设置的签署方流程匹配
        // 公司签署方
        Signatory companySignatory = new Signatory();
        companySignatory.setTenantName(companyName);
        companySignatory.setTenantType("COMPANY");
        companySignatory.setReceiver(new User(signNumber, "MOBILE"));
        companySignatory.setSerialNo(1);
        //List<Action> list =new ArrayList<>();
        //companySignatory.setActions(list);
        draftContract.addSignatory(companySignatory);
        // 公司签署方
        Signatory personalSignatory = new Signatory();
        personalSignatory.setTenantType("COMPANY");
        personalSignatory.setReceiver(new User(shopQiyuesuoInfoDTO.getContact(), shopQiyuesuoInfoDTO.getContactType()));
        personalSignatory.setTenantName(shopQiyuesuoInfoDTO.getCompanyName());
        draftContract.addSignatory(personalSignatory);
        draftContract.setSend(true); // 创建合同草稿并发起合同
        ContractDraftRequest contractDraftRequest = new ContractDraftRequest(draftContract);
        shopQiyuesuoInfoLogSaveBO.setRequetsParam(JSON.toJSONString(contractDraftRequest));
        shopQiyuesuoInfoLogSaveBO.setType(0);
        shopQiyuesuoInfoLogSaveBO.setInfoType(0);

        String response = null;
        try {
            response = client.service(contractDraftRequest);
        } catch (Exception e) {
            shopQiyuesuoInfoLogSaveBO.setStatus(1);
            shopQiyuesuoInfoLogSaveBO.setResponseParam(e.getMessage());
            shopQiyuesuoInfoLogService.add(shopQiyuesuoInfoLogSaveBO);
            throw new Exception("创建合同草稿请求服务器失败，失败原因：" + e.getMessage());
        }
        SdkResponse<Contract> sdkResponse = JSONUtils.toQysResponse(response, Contract.class);
        if (!sdkResponse.getCode().equals(0)) {
            shopQiyuesuoInfoLogSaveBO.setStatus(1);
            shopQiyuesuoInfoLogSaveBO.setResponseParam(sdkResponse.getMessage());
            shopQiyuesuoInfoLogService.add(shopQiyuesuoInfoLogSaveBO);
            throw new Exception("创建合同草稿失败，失败原因：" + sdkResponse.getMessage());
        }
        shopQiyuesuoInfoLogSaveBO.setStatus(0);
        shopQiyuesuoInfoLogSaveBO.setResponseParam(JSON.toJSONString(sdkResponse));
        shopQiyuesuoInfoLogService.add(shopQiyuesuoInfoLogSaveBO);
        return sdkResponse;
    }
}
